package com.qst.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.*;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;
import java.util.Random;

/**
 * 发送邮件工具类
 */
public class EmailUtils {

    /**
     *
     * @param toEmailAddress 目标邮箱
     * @param emailTitle 标题
     * @param emailContent 内容
     * @throws Exception
     */
    public static void sendEmail(String toEmailAddress,String emailTitle,String emailContent){
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        try {
            /**SSL认证，注意腾讯邮箱是基于SSL加密的，所有需要开启才可以使用**/
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.enable", "true");
            props.put("mail.smtp.ssl.socketFactory", sf);

            //创建会话
            Session session = Session.getInstance(props);

            //发送的消息，基于观察者模式进行设计的
            Message msg = new MimeMessage(session);
            msg.setSubject(emailTitle);
            //使用StringBuilder，因为StringBuilder加载速度会比String快，而且线程安全性也不错
            StringBuilder builder = new StringBuilder();
            builder.append("\n"+emailContent);
            builder.append("\n时间 " + new Date());
            msg.setText(builder.toString());
            msg.setFrom(new InternetAddress("3305636904@qq.com"));

            Transport transport = session.getTransport();
            /*从这个邮箱发出信息*/
            transport.connect("smtp.qq.com", "3305636904@qq.com", "byzhskwqtahscjed");
            //发送消息
            transport.sendMessage(msg, new Address[] { new InternetAddress(toEmailAddress) });
            transport.close();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public static String getAuthCode(){
        String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        StringBuilder sb = new StringBuilder(4);
        for(int i=0;i<4;i++){
            char c = str.charAt(new Random().nextInt(str.length()));
            sb.append(c);
        }
        return sb.toString();
    }
}
